import { createRouter, createWebHistory } from 'vue-router'
import Appointments from '../views/Appointments.vue';
import { ElMessage } from 'element-plus'
import Layout from '@/layout/index.vue'  // 用户端布局
import nurseRoutes from './nurse'


const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    meta: { roles: ['user'] },  // 添加用户角色限制
    children: [
      {
        path: 'home',
        component: () => import('@/views/Home.vue'),
        name: 'Home',
        meta: { title: '首页', icon: 'Home' }
      },
      {
        path: 'smart-guide',
        name: 'SmartGuide',
        component: () => import('@/views/SmartGuide.vue'),
        meta: { title: '智能导诊' }
      },
      {
        path: 'ai-chat',
        name: 'AiChat',
        component: () => import('@/views/AiChat.vue'),
        meta: { title: 'AI问诊' }
      },
      {
        path: 'appointments',
        name: 'Appointments',
        component: () => import('@/views/Appointments.vue'),
        meta: { title: '预约陪诊' }
      },
      {
        path: 'about-us',
        name: 'AboutUs',
        component: () => import('@/views/AboutUs.vue'),
        meta: { title: '关于我们' }
      }
    ]
  },
  nurseRoutes,
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

//const routes = [
//  {
//    path: '/home',
//    name: 'Home',
//    component: Home
//  }
//];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫

    // 在路由守卫开头添加调试日志
router.beforeEach((to, from, next) => {
  console.log('[路由守卫] 目标路径:', to.path);
  console.log('[路由守卫] 当前Token:', localStorage.getItem('token'));
  console.log('[路由守卫] 当前角色:', localStorage.getItem('role'));
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 智慧陪诊系统` : '智慧陪诊系统'

  // 获取token和用户角色
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')

  // 白名单路由，不需要验证token
  const whiteList = ['/login']
  if (whiteList.includes(to.path)) {
    // 如果已登录且访问登录页，重定向到对应角色首页
    if (token && role) {
      const roleHomeMap = {
        nurse: '/nurse/center',
        user: '/home'
      }
      next(roleHomeMap[role])
      return
    }
    next()
    return
  }

//  if (to.path === '/home' && !isAuthenticated()) {
//    next('/login'); // 如果未登录，跳转到登录页面
//  } else {
//    next(); // 允许跳转
//  }

  // 未登录跳转到登录页
  if (!token || !role) {
    next(`/login?redirect=${to.path}`)
    return
  }

  // 根据角色进行路由控制
  const roleRouteMap = {
  nurse: {
    prefix: '/nurse',
    home: '/nurse/center',
    allowedPrefixes: ['/nurse', '/appointments'] // 允许访问预约页面
  },
  user: {
    prefix: '/',
    home: '/home',
    allowedPrefixes: [
      '/home',
      '/smart-guide',
      '/ai-chat',
      '/appointments', // 确保包含该路径
      '/about-us'
    ]
  }
}

  const currentRoleRoute = roleRouteMap[role]

  // 如果当前角色不存在，退回登录
  if (!currentRoleRoute) {
    ElMessage.error('无效的用户角色')
    next('/login')
    return
  }

  // 检查是否访问其他角色的路由
  const isAccessingOtherRole = Object.entries(roleRouteMap)
    .filter(([r]) => r !== role)
    .some(([, config]) => {
      return to.path.startsWith(config.prefix) && config.prefix !== '/'
    })

  if (isAccessingOtherRole) {
    ElMessage.error('无权访问该页面')
    next(currentRoleRoute.home)
    return
  }

  // 检查当前角色是否有权访问目标路由
  const hasPermission = currentRoleRoute.allowedPrefixes.some(prefix =>
    to.path === prefix || to.path.startsWith(prefix + '/')
  )

  if (!hasPermission) {
    ElMessage.error('无权访问该页面')
    next(currentRoleRoute.home)
    return
  }

  // 处理根路径重定向
  if (to.path === '/') {
    next(currentRoleRoute.home)
    return
  }

  next()
})

export default router